package com.example.webviewdemo;

import com.example.webviewdemo.slice.MainAbilitySlice;
import ohos.agp.components.webengine.*;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.PixelMap;
import ohos.utils.net.Uri;

import java.io.IOException;
import java.net.URLConnection;

/**
 * WebViewClient 观测Web状态
 * 通过setWebAgent方法设置自定义WebAgent对象，以观测页面状态变更等事件：
 * */
public class ExampleWebAgent extends WebAgent {
    private String virtual = "https://agree/";
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG");
    private MainAbilitySlice context;
    public ExampleWebAgent(MainAbilitySlice mainAbilitySlice) {
        this.context = mainAbilitySlice;
    }


    @Override
    public void onLoadingPage(WebView webview, String url, PixelMap favicon) {
        super.onLoadingPage(webview, url, favicon);
        // 页面开始加载时自定义处理
        HiLog.info(LABEL,"页面开始加载");
    }

    @Override
    public void onPageLoaded(WebView webview, String url) {
        super.onPageLoaded(webview, url);
        // 页面加载结束后自定义处理
        HiLog.info(LABEL,"页面加载结束");
    }

    @Override
    public void onLoadingContent(WebView webview, String url) {
        super.onLoadingContent(webview, url);
        // 加载资源时自定义处理
    }

    @Override
    public ResourceResponse processResourceRequest(WebView webView, ResourceRequest request) {
        Uri requestUri = request.getRequestUrl();
        String url = requestUri.toString();
        HiLog.info(LABEL,"processResourceRequest url = "+ url);
        if(url.startsWith(virtual)){
            // 根据自定义规则访问资源文件
            String rawFilePath = "entry/resources/rawfile/www/" + url.replace(virtual, "");
            HiLog.info(LABEL,"processResourceRequest rawFilePath = "+ rawFilePath);
            String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
            try {
                Resource resource = context.getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
                ResourceResponse response = new ResourceResponse(mimeType, resource, null);
                return response;
            } catch (IOException e) {
                HiLog.info(LABEL, "open raw file failed");
            }
        }
//        if (url.startsWith(virtual)) {
//            // 根据自定义规则访问本地文件
//            String localFile = context.getFilesDir() + url.replace(virtual, "");
//            HiLog.info(TAG, "open local file " + localFile);
//            File file = new File(localFile);
//            if (!file.exists()) {
//                HiLog.info(TAG, "file not exists");
//                return super.processResourceRequest(webview, request);
//            }
//            String mimeType = URLConnection.guessContentTypeFromName(localFile);
//            try {
//                InputStream inputStream = new FileInputStream(file);
//                ResourceResponse response = new ResourceResponse(mimeType, inputStream, null);
//                return response;
//            } catch (IOException e) {
//                HiLog.info(TAG, "open local file failed");
//            }
//        }
        return super.processResourceRequest(webView, request);
    }

    @Override
    public void onError(WebView webview, ResourceRequest request, ResourceError error) {
        super.onError(webview, request, error);
        // 发生错误时自定义处理
        HiLog.info(LABEL, "ERROE= "+error.getErrorCode() + "");
        HiLog.info(LABEL, "ERROEINFO= "+error.getInfo().toString());
    }
    //shouldOverrideUrl 定制网址加载行为,当Web页面进行链接跳转时，WebView默认会打开目标网址，通过以下方式可以定制该行为。
    @Override
    public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {

        if (request == null || request.getRequestUrl() == null) {
            return false;
        }
        // 增加开发者自定义逻辑
        String url = request.getRequestUrl().toString();
        HiLog.info(LABEL,"当Web页面进行链接跳转url = " + url);
        if (url.startsWith("http:") || url.startsWith("https:")) {
            webView.load("https://developer.harmonyos.com/cn/documentation");
            return false;
        } else {
            return super.isNeedLoadUrl(webView, request);
        }
//        return super.isNeedLoadUrl(webView, request);
    }
}
